#include "stdint.h"
#include "string.h"
#include "gd32f10x.h"
#include "systick.h"
#include "DRV_Light_adc.h"


uint32_t light_val;

void Light_ADC_Init(void)
{
    light_val = 0;
    /* enable GPIOA clock */
    rcu_periph_clock_enable(RCU_GPIOA);  
    /* config the GPIO as analog mode */  
    gpio_init(GPIOA, GPIO_MODE_AIN, GPIO_OSPEED_10MHZ, GPIO_PIN_1);
 
    /* enable ADC0 clock */
    rcu_periph_clock_enable(RCU_ADC0);    
    /* config ADC clock */
    rcu_adc_clock_config(RCU_CKADC_CKAPB2_DIV12);
    /* ADC scan mode function enable */
    adc_special_function_config(ADC0, ADC_SCAN_MODE, ENABLE);
    /* ADC trigger config soft trig*/
    adc_external_trigger_source_config(ADC0, ADC_REGULAR_CHANNEL, ADC0_1_2_EXTTRIG_REGULAR_NONE);
    /* ADC data alignment config */
    adc_data_alignment_config(ADC0, ADC_DATAALIGN_RIGHT);
    /* configure the ADC sync mode */
    adc_mode_config(ADC_MODE_FREE);  
    /* ADC channel length config */
    adc_channel_length_config(ADC0, ADC_REGULAR_CHANNEL, 1);
  
    /* ADC regular channel config */
    adc_regular_channel_config(ADC0, 0, ADC_CHANNEL_1, ADC_SAMPLETIME_55POINT5);

    /* ADC external trigger enable */
    adc_external_trigger_config(ADC0, ADC_REGULAR_CHANNEL, ENABLE);
   
    /* enable ADC interface */
    adc_enable(ADC0);
    HAL_Delay(1);
    /* ADC calibration and reset calibration */
    adc_calibration_enable(ADC0);
    HAL_Delay(1);
    nvic_irq_enable(ADC0_1_IRQn,2,0);        //--
    adc_interrupt_enable(ADC0,ADC_INT_EOC);
}

void Light_ADC_Start(void)
{
    adc_software_trigger_enable(ADC0,ADC_REGULAR_CHANNEL);
}

uint32_t Light_ADC_GetValue(void)
{
    return light_val;
}

void ADC0_1_IRQHandler(void)
{
    if(adc_interrupt_flag_get(ADC0,ADC_INT_FLAG_EOC) != RESET)
    {
        adc_interrupt_flag_clear(ADC0,ADC_STAT_STRC|ADC_STAT_EOC);
        light_val = adc_regular_data_read(ADC0);
    }
}

